# -*- encoding: utf-8 -*-
require 'topsdk/version'
require 'topsdk/client'

RAILS_ENV ||= PADRINO_ENV || 'development'
module Topsdk
  class << self

    def current_settings(settings={})
      return @settings if defined? @settings
      @settings = unless settings.empty?
          settings
        else
          load_settings
        end
    end
  
    def get_with(joined_params={})
      Client.new(joined_params, current_settings).get
    end
  
    def post_with(joined_params={})
      Client.new(joined_params, current_settings).post
    end
  
    def ttime(time=nil, type=:dynamic)
      unless time.is_a?(Time)
        return taobao_time
      else
        case type
          when :start
            time.strftime("%Y-%m-%d 00:00:00")
          when :end
            time.strftime("%Y-%m-%d 23:59:59")
          when :dynamic
            time.strftime("%Y-%m-%d %H:%M:%S")
        end
      end
    end
  
    def authorize_url
      "#{current_settings['auth_url']}?appkey=#{current_settings['api_key']}&encode=utf-8"
    end
  
    private
  
    def taobao_time
      get_with({:method => 'taobao.time.get'})['time']
    end
  
    def load_settings
      # 解析配置文件
      file_yml = File.expand_path('./config/taobao.yml') # 应用目录
      file_yml =  File.expand_path('config/taobao.yml', File.dirname(__FILE__))  unless File.exist?(file_yml) # 组件目录 
      YAML.load_file(file_yml)[RAILS_ENV]
    end
  end
end